<?php
/**
 * 飞书登录 - 测试连接
 */

header('Content-Type: application/json');

$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (empty($data['app_id']) || empty($data['app_secret'])) {
    echo json_encode(['success' => false, 'message' => '请填写 App ID 和 App Secret']);
    exit;
}

$appId = trim($data['app_id']);
$appSecret = trim($data['app_secret']);

try {
    // 测试获取 tenant_access_token
    $url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal';
    
    $postData = json_encode([
        'app_id' => $appId,
        'app_secret' => $appSecret
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        echo json_encode(['success' => false, 'message' => 'HTTP 请求失败，状态码：' . $httpCode]);
        exit;
    }
    
    $result = json_decode($response, true);
    
    if (isset($result['code']) && $result['code'] === 0) {
        echo json_encode([
            'success' => true, 
            'message' => '连接成功！应用凭证有效'
        ]);
    } else {
        $errorMsg = $result['msg'] ?? '未知错误';
        echo json_encode([
            'success' => false, 
            'message' => '连接失败：' . $errorMsg
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => '测试失败：' . $e->getMessage()]);
}
